#include "Config.h"

#ifdef WIN32
	#include <shlwapi.h>  
	#pragma comment(lib, "shlwapi.lib")  
#else
	#include <unistd.h>
#endif


CConfig::CConfig()
{
}


CConfig::~CConfig()
{
}

CConfig * CConfig::Instance()
{
	static CConfig _config;
	return &_config;
}

bool CConfig::LoadSetting()
{
	std::string strPath = GetAppPath();
	strPath += "chipDBCvtTool.cfg";

	TiXmlDocument	doc;
	if (!doc.LoadFile(strPath.c_str()))
		return false;

	TiXmlElement*	pRoot = doc.RootElement();
	if (NULL == pRoot)
		return false;

	if (!Ht_ChipDbCvtToolParser::XmlElement2Ht_ChipDbCvtCfg(pRoot, _xmlcfg))
		return false;



	strPath = GetAppPath();
	strPath += "chipResult.xml";

	if (!doc.LoadFile(strPath.c_str()))
		return true;

	pRoot = doc.RootElement();
	if (NULL == pRoot)
		return false;

	if (!Ht_ChipResultParser::XmlElement2Ht_ChipResultCfg(pRoot, _xmlResult))
		return false;


	return true;
}


bool CConfig::Save2Setting()
{
	TiXmlElement*	pRoot = Ht_ChipResultParser::Ht_ChipResultCfg2XmlElement(_xmlResult);
	if (NULL == pRoot)
		return false;

	TiXmlDocument	doc;
	doc.LinkEndChild(pRoot);

	std::string strCfg = GetAppPath() + "chipResult.xml";
	if (!doc.SaveFile(strCfg.c_str()))
		return false;

	return true;
}


std::string CConfig::GetAppPath()
{

	std::string strPath;
#ifdef WIN32

	char pBuf[260];

	GetModuleFileNameA(NULL, pBuf, 260);

	char* pch = strrchr(pBuf, '\\');
	if (pch)
		*(pch + 1) = 0;
	else
		strcat_s(pBuf, _MAX_PATH, "\\");

	strPath = pBuf;
#else

	char buf[260];
	int count = 260;
	int rslt = readlink("/proc/self/exe", buf, count - 1);
	if (rslt < 0 || (rslt >= count - 1))
	{
		return NULL;
	}
	buf[rslt] = '\0';
	for (int i = rslt; i >= 0; i--)
	{
		if (buf[i] == '/')
		{
			buf[i + 1] = '\0';
			break;
		}
	}
	strPath = buf;

#endif

	return strPath;
}
